package com.wx.lambda.ii.chapter11;

import cn.hutool.core.date.TimeInterval;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Slf4j
public class ShopTest {
    public static void main(String[] args) {
        Shop shop = new Shop("TB");
        TimeInterval timer = new TimeInterval();
        Future<Double> price = shop.getPrice("iphone 15 pro max");
        log.info("干点其他的事情");

        Double aDouble = null ;
        try {
            aDouble = price.get();
        } catch (InterruptedException | ExecutionException e) {
            log.error(e.getMessage(), e);
        }
        log.info("price={},耗时：{}", aDouble, timer.intervalRestart());

        Future<Double> priceAsync = shop.getPriceAsync("iphone 15 pro max");
        Double aDouble1;
        try {
            aDouble1 = priceAsync.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        log.info("aDouble1={},耗时：{}", aDouble1, timer.intervalRestart());
        getOptimum1();
        log.info("getOptimum1,耗时：{}", timer.intervalRestart());
        getOptimum2();
        log.info("getOptimum2,耗时：{}", timer.intervalRestart());
    }

    /**
     * 获得最佳效果1
     */
    static void getOptimum1(){
        List<Shop> shops = Arrays.asList(
                new Shop("tb"),
                new Shop("pdd"),
                new Shop("JD"),
                new Shop("MT"));

        shops.stream()
                .map(shop -> {
                    try {
                        return String.format("%s 找到价格 %.2f",shop.getName(),shop.getPrice("iphone 15 pro max").get());
                    } catch (InterruptedException | ExecutionException e) {
                        throw new RuntimeException(e);
                    }
                })
                .forEach(log::info);

    }

    /**
     * 获得最佳效果2
     * 使用并行流
     */
    static void getOptimum2(){
        List<Shop> shops = Arrays.asList(
                new Shop("tb"),
                new Shop("pdd"),
                new Shop("JD"),
                new Shop("MT"));

        shops.stream()
                .parallel()
                .map(shop -> {
                    try {
                        return String.format("%s 找到价格 %.2f",shop.getName(),shop.getPrice("iphone 15 pro max").get());
                    } catch (InterruptedException | ExecutionException e) {
                        throw new RuntimeException(e);
                    }
                })
                .forEach(log::info);

    }

}
